import { getCookie } from '@/utils/cookie'
import axios from 'axios'
import router from '../router/index'
import { showToast } from 'vant'
import { useDebounceFn } from '@vueuse/core'

let loadingReqCount = 0 // 统计loading个数
let loadingInstance: any = null // 正在loading的实例

function showLoading () {
  if (loadingReqCount === 0 && !loadingInstance) {
    loadingInstance = showToast({
      type: 'loading',
      message: '加载中...',
      forbidClick: true, // 不可点击关闭
      duration: 0 // 无限随间
    })
  }
  loadingReqCount++
}

function closeLoading () {
  loadingReqCount--
  loadingReqCount = Math.max(loadingReqCount, 0) // 保证大于等于0
  if (loadingReqCount === 0 || loadingInstance) {
    hideLoading()
  }
}

// 关闭loading防抖，延迟300ms执行，合并该时延内的间断请求。
const hideLoading = useDebounceFn(() => {
  // loadingReqCount 需要二次判断，因为后续接口调用会增加这个值，就不能直接关闭
  if (loadingReqCount === 0) {
    loadingInstance.close()
    loadingInstance = null
  }
}, 300)

export function request (config: any) {
  const instance = axios.create({
    baseURL: 'https://api.shop.eduwork.cn/',
    timeout: 5000
  })

  // 请求拦截
  instance.interceptors.request.use(config => {
    showLoading()
    const token = getCookie('token')
    if (token) {
      config.headers.Authorization = 'Bearer' + token
    }
    return config
  }, err => {
    closeLoading()
    console.log(err)
  })

  // 响应拦截
  instance.interceptors.response.use(res => {
    closeLoading()
    return res
  }, err => {
    closeLoading()
    if (err.code === 'ECONNABORTED') { // 请求超时
      if (router.currentRoute.value.path === '/login' || router.currentRoute.value.path === '/register') {
        showToast({ type: 'fail', message: '网络超时, 请重新操作' })
      } else {
        return Promise.reject(err)
      }
    } else { // 没有请求超时
      if (err.status === 401 && (router.currentRoute.value.path === '/login' || router.currentRoute.value.path === '/register')) {
        showToast('邮箱或密码有误!')
      } else if (err.status === 401) { // 未授权
        showToast({
          type: 'fail',
          message: '请先登录呀',
          duration: 1000,
          forbidClick: true,
          onClose: () => {
            router.push('/login')
          }
        })
      } else {
        console.log(err, 123)
        showToast({ type: 'fail', message: err.response.data.errors[Object.keys(err.response.data.errors)[0]][0], duration: 1000 })
      }
    }
    // return Promise.reject(err)
  })

  return instance(config)
}
